<template>
  <div class="streaming-view">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>流媒体播放</span>
          <div class="header-controls">
            <el-select v-model="selectedDevice" placeholder="选择设备" @change="onDeviceChange">
              <el-option
                v-for="device in devices"
                :key="device.id"
                :label="device.name"
                :value="device.id"
              />
            </el-select>
            <el-select v-model="selectedChannel" placeholder="选择频道" @change="onChannelChange">
              <el-option
                v-for="channel in channels"
                :key="channel.id"
                :label="channel.name"
                :value="channel.id"
              />
            </el-select>
          </div>
        </div>
      </template>
      
      <div class="streaming-container">
        <div class="video-grid" :class="`grid-${viewMode}`">
          <div 
            v-for="(stream, index) in activeStreams" 
            :key="index"
            class="video-item"
            :class="{ active: selectedStreamIndex === index }"
            @click="selectStream(index)"
          >
            <div class="video-wrapper">
              <video 
                :ref="el => videoRefs[index] = el"
                controls 
                autoplay
                muted
                :poster="stream.poster"
                class="video-player"
              >
                <source :src="stream.url" type="application/x-mpegURL">
                您的浏览器不支持视频播放
              </video>
              <div class="video-overlay">
                <div class="video-info">
                  <h4>{{ stream.name }}</h4>
                  <p>{{ stream.resolution }} | {{ stream.status }}</p>
                </div>
                <div class="video-controls">
                  <el-button size="small" @click.stop="togglePlay(index)">
                    {{ stream.playing ? '暂停' : '播放' }}
                  </el-button>
                  <el-button size="small" @click.stop="takeSnapshot(index)">截图</el-button>
                  <el-button size="small" @click.stop="toggleFullscreen(index)">全屏</el-button>
                </div>
              </div>
            </div>
          </div>
        </div>
        
        <div class="control-panel">
          <div class="view-controls">
            <span>显示模式：</span>
            <el-radio-group v-model="viewMode">
              <el-radio-button label="1">单画面</el-radio-button>
              <el-radio-button label="4">四画面</el-radio-button>
              <el-radio-button label="9">九画面</el-radio-button>
              <el-radio-button label="16">十六画面</el-radio-button>
            </el-radio-group>
          </div>
          
          <div class="stream-controls">
            <el-button type="primary" @click="addStream">添加流</el-button>
            <el-button @click="removeStream">移除流</el-button>
            <el-button @click="startAllStreams">全部播放</el-button>
            <el-button @click="stopAllStreams">全部停止</el-button>
          </div>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'

const selectedDevice = ref('')
const selectedChannel = ref('')
const selectedStreamIndex = ref(0)
const viewMode = ref('4')
const videoRefs = ref([])

const devices = ref([
  { id: 1, name: '前门摄像头' },
  { id: 2, name: '后门摄像头' },
  { id: 3, name: '大厅摄像头' }
])

const channels = ref([
  { id: 1, name: '主码流', deviceId: 1 },
  { id: 2, name: '子码流', deviceId: 1 },
  { id: 3, name: '主码流', deviceId: 2 }
])

const activeStreams = reactive([
  {
    id: 1,
    name: '前门摄像头 - 主码流',
    url: '',
    resolution: '1920x1080',
    status: '在线',
    playing: false,
    poster: '/placeholder-video.jpg'
  }
])

onMounted(() => {
  initializeStreaming()
})

const initializeStreaming = () => {
  // TODO: 初始化流媒体配置
  console.log('初始化流媒体播放器')
}

const onDeviceChange = () => {
  // TODO: 设备变更时更新频道列表
  console.log('设备变更:', selectedDevice.value)
}

const onChannelChange = () => {
  // TODO: 频道变更时更新流地址
  console.log('频道变更:', selectedChannel.value)
}

const selectStream = (index) => {
  selectedStreamIndex.value = index
}

const togglePlay = async (index) => {
  const stream = activeStreams[index]
  const video = videoRefs.value[index]
  
  try {
    if (stream.playing) {
      video?.pause()
      stream.playing = false
    } else {
      await video?.play()
      stream.playing = true
    }
  } catch (error) {
    ElMessage.error('播放控制失败')
  }
}

const takeSnapshot = (index) => {
  try {
    // TODO: 实现截图功能
    ElMessage.success('截图成功')
  } catch (error) {
    ElMessage.error('截图失败')
  }
}

const toggleFullscreen = (index) => {
  const video = videoRefs.value[index]
  if (video) {
    if (document.fullscreenElement) {
      document.exitFullscreen()
    } else {
      video.requestFullscreen()
    }
  }
}

const addStream = () => {
  if (activeStreams.length >= parseInt(viewMode.value)) {
    ElMessage.warning(`当前显示模式最多支持${viewMode.value}个流`)
    return
  }
  
  const newStream = {
    id: Date.now(),
    name: `新流 ${activeStreams.length + 1}`,
    url: '',
    resolution: '1920x1080',
    status: '离线',
    playing: false,
    poster: '/placeholder-video.jpg'
  }
  
  activeStreams.push(newStream)
}

const removeStream = () => {
  if (activeStreams.length > 1) {
    activeStreams.splice(selectedStreamIndex.value, 1)
    if (selectedStreamIndex.value >= activeStreams.length) {
      selectedStreamIndex.value = activeStreams.length - 1
    }
  } else {
    ElMessage.warning('至少需要保留一个流')
  }
}

const startAllStreams = () => {
  activeStreams.forEach((stream, index) => {
    if (!stream.playing) {
      togglePlay(index)
    }
  })
}

const stopAllStreams = () => {
  activeStreams.forEach((stream, index) => {
    if (stream.playing) {
      togglePlay(index)
    }
  })
}
</script>

<style scoped>
.streaming-view {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-controls {
  display: flex;
  gap: 10px;
}

.streaming-container {
  margin-top: 20px;
}

.video-grid {
  display: grid;
  gap: 10px;
  margin-bottom: 20px;
}

.grid-1 {
  grid-template-columns: 1fr;
}

.grid-4 {
  grid-template-columns: repeat(2, 1fr);
}

.grid-9 {
  grid-template-columns: repeat(3, 1fr);
}

.grid-16 {
  grid-template-columns: repeat(4, 1fr);
}

.video-item {
  position: relative;
  border: 2px solid transparent;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
  transition: border-color 0.3s;
}

.video-item.active {
  border-color: var(--el-color-primary);
}

.video-wrapper {
  position: relative;
  width: 100%;
  height: 0;
  padding-bottom: 56.25%; /* 16:9 aspect ratio */
}

.video-player {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  color: white;
  opacity: 0;
  transition: opacity 0.3s;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
  padding: 10px;
}

.video-item:hover .video-overlay {
  opacity: 1;
}

.video-info h4 {
  margin: 0 0 5px 0;
  font-size: 14px;
}

.video-info p {
  margin: 0;
  font-size: 12px;
  opacity: 0.8;
}

.video-controls {
  display: flex;
  gap: 5px;
}

.control-panel {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px;
  background: var(--el-bg-color-page);
  border-radius: 8px;
}

.view-controls {
  display: flex;
  align-items: center;
  gap: 10px;
}

.stream-controls {
  display: flex;
  gap: 10px;
}
</style>